<?php
namespace app\shop\controller\api;

use app\shop\library\ApiController;
use app\shop\library\Member;
use app\shop\library\coupon\Coupon;
use app\shop\library\order\Stock;
use app\shop\library\Goods as libGoods;
use cubox\Cache;

class Goods extends ApiController{

    protected int $listCacheTime = 3600;
    public function onList(){
        $this->listCacheTime = $this->app->config('api')->listCacheTime??3600;
        $selectType  = $this->post('selectType','goods');
        $page        = $this->post('page',$this->check()->type('int')->default(1));
        $pageSize    = $this->post('number',$this->check()->type('int')->default(10));
        $order       = $this->post('order','newDesc');
        $tag         = $this->post('tag','');
        $cateId      = $this->post('cateId',$this->check()->type('int')->default(0));
        $goodsIds    = $this->post('goodsIds',$this->check()->type('string')->default(''));
        $specId      = $this->post('specId',$this->check()->type('int'));
        $cache = $this->cache();

        $random = true;

        if ($selectType=='like'){

            if (Member::$id!=''){
                
                //获取tag
                $tag = '';
                $tagKey = $this->getCacheName('user_tag',Member::$id);
                if ($cache->exists($tagKey)){
                   $tag  =  $cache->get($tagKey);
                }else{
                    $data = $this->model('Member')->getId(Member::$id);
                    $tag = $data['tag'];
                    $cache->set($tagKey,$tag);
                }

                if ($tag!=''){
                    $random = false;
                    $re = $this->tagList($tag,$page,$pageSize);
                }

            }

        }elseif ($selectType=='tag'){
            if ($tag!=''){
                $random = false;
                $re = $this->tagList($tag,$page,$pageSize);
            }

        }else{
            //读取缓存
            $re  = [];
            $key = $this->getCacheName('goodslist',md5(implode('',$this->posts)));
            
            if ($cache->exists($key)){
                $re  = json_decode($cache->get($key)??'[]',true);
            }else{
                $goods = $this->model('Goods');
                
                $re = [];

                switch($selectType){
                    case 'category':
                        if($cateId){
                            $random = false;
                            $goods->where('cate_id',$cateId);
                        }
                    break;
                    case 'goods':
                        if ($goodsIds!='') {
                            $random = false;
                            $goods->where('goods_id','in',$goodsIds);
                        }
                    break;
                    case 'spec':
                        if($specId){
                            $random = false;
                            $goods->where('spec_id',$specId);
                        }
                    break;
                }

                if ($selectType !='goods'){
                    switch($order){
                        case 'newDesc':
                            $goods->order('goods_id','desc');
                        break;
                        case 'newAsc':
                            $goods->order('goods_id','asc');
                        break;
                        case 'salesDesc':
                            $goods->order('sales','desc');
                        break;
                        case 'salesAsc':
                            $goods->order('sales','asc');
                        break;
                        case 'priceDesc':
                            $goods->order('price','desc');
                        break;
                        case 'priceAsc':
                            $goods->order('price','asc');
                        break;
                    }
                }

                if (!$random){
                    $goods->field('goods_id')->where('status','sale')->page($page,$pageSize);
                     
                    $data = [];
                    
                    foreach($goods->getData() as $v){
                        $data[] = libGoods::get($v['goods_id']);
                    }

                    $re['list'] =  $data;
                    $re['total'] = $goods->total;
                    $re['pageCount'] =   $goods->pageCount;
                    $cache->set($key,json_encode($re),$this->listCacheTime);
                }
            }

            
        }

        if ($random){
            $re = $this->randomList($page,$pageSize);
        }

        return $re;
    }


    private function randomList($page,$pageSize){

        $key = $this->getCacheName('goodslist_random');
        $listKey = $key.'_list';
        $cache = $this->cache();
        $data  = [];
        if ($cache->exists($key) && $cache->exists($listKey)){
            $data  = json_decode($cache->get($key)??'[]',true);
            $list  = $cache->lRange($listKey,$pageSize*($page-1),$pageSize*$page);
            foreach($list as $v) $data['list'][] = json_decode($v,true);
        }else{
            //每个类型的深度

            $deepPageSize =  $this->app->config('api')->randomListDeep??100;
            $goods = $this->model('Goods');
            //新商品
            $re = $goods->field('goods_id')->where('status','sale')->order('goods_id','desc')->limit(0,$deepPageSize)->getData();
            //价格
            $re = array_merge($re,$goods->where('status','sale')->field('goods_id')->order('price','desc')->limit(0,$deepPageSize)->getData());
            //销量
            $re = array_merge($re,$goods->where('status','sale')->field('goods_id')->order('sales','desc')->limit(0,$deepPageSize)->getData());
            
            $_re = [];
            foreach($re as $v){
                if (in_array($v['goods_id'],$_re)){
                    continue;
                }else{
                    $_re[] = $v['goods_id'];
                }
            }
            
            shuffle($_re);
            $list = [];

            foreach($_re as $v){
                $list[] = libGoods::get($v);
            }
            
            $data['pageCount'] = ceil(count($list)/$pageSize);
            $data['total'] = count($list);
            $data['list'] = array_slice($list,$pageSize*($page-1),$pageSize);
            $cache->set($key,json_encode($data),$this->listCacheTime);

            $cache->delete($listKey);
            foreach($list as $v) $cache->lPush($listKey,json_encode($v));
            $cache->expire($listKey,$this->listCacheTime);

        }

        return $data;
    }

    private function tagList($tag,$page,$pageSize){
        $key = $this->getCacheName('goodslist_tag_'.md5($tag));
        $listKey = $key.'_list';
        $cache = $this->cache();
        $data  = [];

        if ($cache->exists($key) && $cache->exists($listKey)){
            $data  = json_decode($cache->get($key)??'[]',true);
            $list  = $cache->lRange($listKey,$pageSize*($page-1),$pageSize*$page);
            foreach($list as $v) $data['list'][] = json_decode($v,true);
        }else{
            $deepPageSize =  $this->app->config('api')->tagListDeep??100;
            $tagArr = explode(',',$tag);
            $goods = $this->model('Goods');
            $re = [];
            foreach($tagArr as $v){
                $re = array_merge($re,
                    $goods->field('goods_id')->where('status','sale')->where('tag','like','%'.$tag.'%')->order('goods_id','desc')->page(1,$deepPageSize)->getData()
                );
            }            
            $_re = [];
            foreach($re as $v){
                if (in_array($v['goods_id'],$_re)){
                    continue;
                }else{
                    $_re[] = $v['goods_id'];
                }
            }
            
            shuffle($_re);
            $list = [];

            foreach($_re as $v){
                $list[] = libGoods::get($v);
            }

            $data['pageCount'] = ceil(count($list)/$pageSize);
            $data['total'] = count($list);
            $cache->set($key,json_encode($data),$this->listCacheTime);

            $cache->delete($listKey);
            foreach($list as $v) $cache->lPush($listKey,json_encode($data));
            $cache->expire($listKey,$this->listCacheTime);
        }

        return  $data;
    }

    
    public function onDetail(){
        $goods_id = $this->post('goods_id',$this->check()->type('int')->required());
        $data =  libGoods::get($goods_id);
        
        if ($data=='off'){
            throw new \Exception('商品已下架');
        }

        $cachename  = $this->getCacheName('goods:content',$goods_id);
        $cache = $this->cache();
        if ($cache->exists($cachename)){
            $data['content'] = $cache->get($cachename);
        }else{
            $row = $this->model('GoodsDetail')->getId($goods_id);

            if ($row){
                $data['content'] = $row['content'];
            }else{
                $data['content'] = '';
            }

            $cache->set($cachename,$data['content'],3600);  
        }

        return $data;
    }
}